//
//  DeviceSearchListView.m
//  sentorise
//
//  Created by admin on 2025/8/25.
//

#import "DeviceSearchListView.h"
#import "BTManager.h"
#import "GlobalDefine.h"
#import "DeviceSearchItemTableViewCell.h"
#import "DeviceConnectCheckView.h"
#import "BlutoothGroupModel.h"
#import "DeviceScanResultViewController.h"
#import "ProgressHUD.h"

@interface DeviceSearchListView()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *descLabel;
@property (weak, nonatomic) IBOutlet UILabel *refreshLabel;

@property (nonatomic, strong) UINavigationController *nv;
@property (nonatomic, strong) NSMutableArray<CBPeripheral *> *dataSource;

@end

@implementation DeviceSearchListView

+ (void)show:(UINavigationController *)nv {
    DeviceSearchListView *view = (DeviceSearchListView *)[[[NSBundle mainBundle] loadNibNamed:@"DeviceSearchListView" owner:self options:nil] firstObject];
    view.frame = [[UIScreen mainScreen] bounds];
    view.nv = nv;
    [[UIApplication sharedApplication].delegate.window addSubview:view];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.titleLabel.text = NSLocalizedString(@"Search via Biluetoot", nil);
    self.descLabel.text = NSLocalizedString(@"Nearby Bluetooth dev", nil);
    self.refreshLabel.text = NSLocalizedString(@"Refresh", nil);

    self.dataSource = [[NSMutableArray alloc] init];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"DeviceSearchItemTableViewCell" bundle:nil] forCellReuseIdentifier:@"DeviceSearchItemTableViewCell"];
    
    [[BTManager sharedBTManager] retartScan];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchDevices:) name:kBTSearchDevices object:nil];
}

- (void)searchDevices:(NSNotification *)nf {
    NSArray *list = nf.object;
    [self.dataSource removeAllObjects];
    NSMutableArray *arr = [NSMutableArray array];
    NSString *listStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"BatteryBluList"] ?: @"";
    if (listStr.length) {
        NSArray *dataArray = [BlutoothModel covertToModelList:listStr];
        [arr addObjectsFromArray:dataArray];
    }
    if (arr.count) {
        for (CBPeripheral *p in list) {
            BOOL isExtence = NO;
            for (BlutoothModel *m in arr) {
                if ([m.uuid isEqualToString:p.identifier.UUIDString]) {
                    isExtence = YES;
                }
            }
            if (!isExtence) {
                [self.dataSource addObject:p];
            }
        }
    }else {
        [self.dataSource addObjectsFromArray:list];
    }
    [self.tableView reloadData];
}

- (IBAction)actionClose:(id)sender {
    [self removeFromSuperview];
    [[NSNotificationCenter defaultCenter] postNotificationName:kBTAddViewDismiss object:nil];
}

- (IBAction)actionRefresh:(id)sender {
    [[BTManager sharedBTManager] retartScan];
    [self.dataSource removeAllObjects];
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DeviceSearchItemTableViewCell *cell = (DeviceSearchItemTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"DeviceSearchItemTableViewCell"];
    NSString *name = [[BTManager sharedBTManager].diviceNameDict objectForKey:self.dataSource[indexPath.section].name];
    name = name.length>0 ? name : self.dataSource[indexPath.section].name;
    cell.nameLabel.text = name;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForFooterInSection:(NSInteger)section {
    return 16;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 16)];
    view.backgroundColor = [UIColor clearColor];
    
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DeviceScanResultViewController *vc = [[DeviceScanResultViewController alloc] initWithNibName:@"DeviceScanResultViewController" bundle:nil];
    NSDictionary *dict = [[BTManager sharedBTManager].advertisementDataDict objectForKey:self.dataSource[indexPath.section].name] ?: @{};
    NSData *data = [dict objectForKey:@"kCBAdvDataManufacturerData"];
    Byte *receieveData = (Byte*)data.bytes;
    NSMutableArray *macs = [NSMutableArray array];
    for (NSInteger i=data.length-4; i>=0; i--) {
        [macs addObject:[NSString stringWithFormat:@"%02X", receieveData[i]]];
        if (macs.count >= 6) {
            break;
        }
    }
    NSString *mac = [macs componentsJoinedByString:@":"];
    if (macs.count != 6) {
        [ProgressHUD showErrorMessage:@"Bluetooth matching failed, please try again"];
        return;
    }
    [self removeFromSuperview];
    vc.mac = mac;
    vc.type = 0;
    vc.peripheral = self.dataSource[indexPath.section];
    [self.nv pushViewController:vc animated:YES];
}



@end
